package com.yx;

import java.util.concurrent.CountDownLatch;

/**
 * @author yx
 * @date 2025-04-06 10:22
 * @description:
 */
public class Latch {

    public static void main(String[] args) throws InterruptedException {
        timeTasks(3, () ->{
            System.out.println(Thread.currentThread().getName()  + "完成任务");
        });
    }

    public static long timeTasks(int nThread, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(nThread);
        for (int i = 0; i < nThread; i++) {
            Thread thread = new Thread(() -> {
                try {
                    System.out.println("现在线程" + Thread.currentThread().getName() + "正在等待");
                    startGate.await();
                    try {
                        task.run();
                    } finally {
                        endGate.countDown();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();
        }
        long start = System.currentTimeMillis();
        startGate.countDown();
        endGate.await();
        long end = System.currentTimeMillis();
        return end - start;
    }

}
